package org.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 全局拦截器 ， 作用于所有的请求
 * 对请求的API调用： 记录接口的请求时间
 */
@Slf4j
public class ApiLoggingFilter implements GlobalFilter, Ordered {

    private static final String START_TIME = "startTime";
    /**
     * nginx 需要配置
     * https://blog.csdn.net/xqhys/article/details/81782633
     */
    private static final String X_REAL_IP = "X-Real-IP";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String info = String.format("Method:{%s} Host:{%s} Path:{%s}}",
                Objects.requireNonNull(exchange.getRequest().getMethod()).name(),
                exchange.getRequest().getURI().getHost(),
                exchange.getRequest().getURI().getPath());
        if (log.isDebugEnabled()) {
            log.debug(info);
        }
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long executeTime = System.currentTimeMillis() - startTime;
                // 请求头中配置
                List<String> ips = exchange.getRequest().getHeaders().get(X_REAL_IP);
                String ip = ips != null ? ips.get(0) : "no ip";
                String api = exchange.getRequest().getURI().getPath();
                int code = exchange.getResponse().getStatusCode() != null ?
                        exchange.getResponse().getStatusCode().value() : 500;
                if (log.isDebugEnabled()) {
                    log.debug("来自IP地址：{} 的请求接口：{}，响应状态码：{}，请求耗时：{}ms", ip, api, code, executeTime);
                }
            }
        }));
    }

    /**
     * 最高优先级
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
